/*
 * Copyright (C) 2025 ameise <ameise.wang@gmail.com> - All Rights Reserved
 *
 * This file is part of e3lock.
 *
 * e3lock is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * e3lock is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with e3lock. If not, see <https://www.gnu.org/licenses/>.
 */

//go:build !debug

package e3lock

import (
	"context"
	"runtime"
)

func (ts *redisLock) Lock() {
	const maxBlock = 64
	block := 1
	ts.mu.Lock()
	for {
		if ts.doRedisLock() {
			break
		}
		for i := 0; i < block; i++ {
			runtime.Gosched()
		}
		if block < maxBlock {
			block <<= 1
		}
	}
}

func (ts *redisLock) TryLock() bool {
	if !ts.mu.TryLock() {
		return false
	}
	if !ts.doRedisLock() {
		ts.mu.Unlock()
		return false
	}
	return true
}

func (ts *redisLock) Unlock() {
	if ts.isLock.CompareAndSwap(true, false) {
		ts.cli.EvalSha(context.Background(), scriptUnlockSHA, []string{ts.key}, ts.token)
		ts.tr.Reset(0)
		ts.wg.Wait()
		ts.tr.Stop()
		select {
		case <-ts.tr.C:
		default:
		}
		ts.tr = nil
		ts.mu.Unlock()
	}
}
